package com.yylc.cscore.controller;

import cn.hutool.core.util.StrUtil;
import com.yylc.cscore.dao.CustomerDao;
import com.yylc.cscore.entity.CustomerEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author xiangnan
 */
@RestController
@RequestMapping("/security")
public class LoginController {
    private Logger logger = LogManager.getLogger();

    @Resource
    private CustomerDao customerDao;

    @PostMapping("/login")
    public Object login(String username, String password, HttpSession session) {
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            logger.info("账户名或密码为空：{} {}", username, password);
            throw new RuntimeException("账户名或密码为空");
        }

        List<CustomerEntity> list = customerDao.selectListByPassword(password);
        list = list.stream()
                .filter(item -> username.equals(item.getServiceId()) || username.equals(item.getServiceName()))
                .collect(toList());
        if (list.isEmpty()) {
            throw new RuntimeException("账户名或密码错误");
        } if (list.size() > 1) {
            throw new RuntimeException("账户名冲突，请联系管理员");
        }

        CustomerEntity user = list.get(0);
        logger.info("登录成功，username={}, user={}", username, user);
        session.setAttribute("user", user);
        return user;
    }

    @GetMapping("/login")
    public Object getLogin(HttpSession session) {
        return session.getAttribute("user") == null ? -1 : 0;
    }

    @GetMapping("/login/session")
    public Object getLoginSession(HttpSession session) {
        Object user = session.getAttribute("user");
        if (user == null) {
            throw new RuntimeException("你还未登录");
        }

        return user;
    }

    @DeleteMapping("/login")
    public Object logout(HttpSession session) {
        Object user = session.getAttribute("user");
        if (user == null) {
            throw new RuntimeException("你还未登录");
        }

        session.removeAttribute("user");
        return 0;
    }

}
